package com.dq.usercenter.controller;

import com.alibaba.fastjson.JSON;
import com.dq.commonutils.jwt.JwtUtil;
import com.dq.commonutils.pojo.DqException;
import com.dq.commonutils.vo.Result;
import com.dq.usercenter.entity.UcenterMember;
import com.dq.usercenter.mapper.UcenterMemberMapper;
import com.dq.usercenter.properties.WxProperties;
import com.dq.usercenter.service.UcenterMemberService;
import com.dq.usercenter.utils.HttpClientUtils;
import com.dq.usercenter.vo.UserMemberVo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;



/**
 * @project: guli_parent
 * @ClassName: WxApiController
 * @author: dq
 * @creat: 2022/8/10 16:19
 */
@Controller
@RequestMapping("/api/ucenter/wx")
@Slf4j
// @CrossOrigin
public class WxApiController {
    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private UcenterMemberService userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 跳转页面
     *
     * @return
     */
    @GetMapping("callback")
    public String callback(String code, String state) {
        /**
         * 1. 拿到code去访问微信提供的固定的地址   https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
         * 2. 获取到access_token   openid
         * 3. 再去请求微信固定的地址
         * 4. 最终才能获取到扫码人的信息
         */

        try {
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //1 拼接地址 请求Httpclient
            String AccessTokenUrl = String.format(baseAccessTokenUrl, wxProperties.getAppId(), wxProperties.getAppSecret(), code);
            String accessTokenInfo = HttpClientUtils.get(AccessTokenUrl);
            /*
            返回字符串 变为json 获取access_token   openid
            {"access_token":"59_N9B0rw4YdM3Z8rhXfft4aN8dVJVCtdlPJ-dxLQgQYDBAK9-81H69AXVUX2iNKCD8AnBNtbdMhVcNyIJvGB8kjTaaO1S78hiv7NdO4_R8cnA",
            "expires_in":7200,
            "refresh_token":"59_Ea5VHQr4s_0GPQTowX4B4_Mtnb64hswxAlug4Epkx_2wjc3G7cv5YAS5cmL_gFTJxXjUfZjSOOzJPiojxpVQDIoK-roIIlSPSSN4bGGCJao",
            "openid":"o3_SC56LqS0BCJuHfmG-1DuYtn0g",
            "scope":"snsapi_login",
            "unionid":"oWgGz1M8drEOugSBfFu4qy-M5O9k"}
             */

            //2 利用Gson转化数据 请求下一个地址获取最终信息
            Gson gson = new Gson();
            HashMap map = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) map.get("access_token");
            String openid = (String) map.get("openid");


            //判断数据库中是否存在相同的信息
            UcenterMember userMember = userMapper.getOpenidMember(openid);
            if (userMember == null) {

                //把第三步放在if判断里面  防止多次添加数据
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(userInfo);
            /*
            userInfo的信息
            {"openid":"o3_SC56LqS0BCJuHfmG-1DuYtn0g",
            "nickname":"ᝰꫀꪶꪖρડ꧖ꦿ🐋",
            "sex":0,"language":"","city":"","province":"","country":"",
            "headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/Dn0EVpaEjkI4Tb2hbrlcQmtoJfyNychHVd2ibG45ySWlmAtLVUsx3IVqnohQ8tpSwcaDcXyDpeDEDp8L8h8iaofA\/132",
            "privilege":[],"unionid":"oWgGz1M8drEOugSBfFu4qy-M5O9k"}
             */
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");

                //把扫描人信息加入数据库
                userMember = new UcenterMember();
                userMember.setNickname(nickname);
                userMember.setAvatar(headimgurl);
                userMember.setOpenid(openid);
                userMapper.save(userMember);
            }
            //如何把这个数据传到前端  jwt
            String token = JwtUtil.createToken(userMember.getId(), userMember.getNickname());
            UserMemberVo userMemberVo = new UserMemberVo();
            BeanUtils.copyProperties(userMember, userMemberVo);
            log.info("------------WX登录-----------");
            log.info("------------存入redis-----------");
            redisTemplate.opsForValue().set("TOKEN-" + token, JSON.toJSONString(userMemberVo), 1, TimeUnit.DAYS);
            log.info("-----------------------------");
            return "redirect:http://localhost:3000?token=" + token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DqException(20001, "登录失败");
        }
    }

    /**
     * 微信登录
     *
     * @return
     * @url http://localhost:8160/api/ucenter/wx/login
     */
    @GetMapping("login")
    public String getWxCode() {
        //请求微信地址
        String baseUrl =
                "https://open.weixin.qq.com/connect/qrconnect?" +
                        "appid=%s" +
                        "&redirect_uri=%s" +
                        "&response_type=code" +
                        "&scope=snsapi_login" +
                        "&state=%s" +
                        "#wechat_redirect";
        //对redirectUrl编码
        String redirectUrl = wxProperties.getRedirectUrl();
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = String.format(
                baseUrl,
                wxProperties.getAppId(), wxProperties.getRedirectUrl(), "dq");

        return "redirect:" + url;
    }
}
